package com.backend.controller;

import com.backend.entity.SessionMovie;
import com.backend.entity.Session;
import com.backend.repository.MovieRepository;
import com.backend.repository.SessopnMovieRepository;
import com.backend.entity.Movie;
import com.backend.repository.SessionRepository;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;


@RestController
@RequestMapping("/movie")
@CrossOrigin
public class MovieController {
    @Autowired
    MovieRepository movieRepository;
    @Autowired
    SessionRepository sessionRepository;
    @Autowired
    SessopnMovieRepository sessionMovieRepository;

    @GetMapping("/get")
    public Result getById(@Param("id") Integer id){
        System.out.println("123");
        System.out.println(id);
        Optional<Movie> movie = movieRepository.findById(id);
        if (movie.isPresent()) {
            return Result.success(movie);
        } else {
            return Result.error(201, "movie"+id+"不存在");
        }
    }

    @GetMapping("/cinemaList")
    public Result getByMovieId(@Param("movie_id") Integer movie_id) {
        List<SessionMovie> sessionMovies = sessionMovieRepository.findByMovie_id(movie_id);
        System.out.println(sessionMovies);
        System.out.println(movie_id);
        return Result.success(sessionMovies);
    }

    @PostMapping("/updateSeats")
    public Result updateSeats(@RequestBody Map<String, Object> map) {
        System.out.println(map.get("id")+","+map.get("seats"));
        Integer id = Integer.valueOf(map.get("id").toString());
        String seats = map.get("seats").toString();
//        return Result.success();
        Optional<Session> op = sessionRepository.findById(id);
        System.out.println(seats);
        if (op.isPresent()) {
            Session session = op.get();
            session.setSeats(seats);
            sessionRepository.save(session);
            return Result.success();
        } else {
            return Result.error(201, "session"+id+"不存在");
        }
    }
}
